﻿using SkiaSharp;
using System;
using System.Data;
using System.Data.SqlClient;
using XingLucifer.IBase.Enums;

namespace UIWindows.Tools.Helper
{
    public class SqlServerHelper
    {

        public SqlServerHelper(string connString)
        {
            _connString = connString;
        }

        // string connString = "server=DESKTOP-BQDF638;database=test_four;uid=sa;pwd=123456";
        string _connString = "server=192.168.102.100;uid=sa;pwd=kinte123;database=JLdb";

        SqlConnection conn = null;
        public bool OpenDB()
        {
            try
            {
                conn = new SqlConnection(_connString);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                $"[数据库]：连接成功".RunLog(MessageLevelType.成功);
                return true;
            }
            catch (Exception ex)
            {
                $"[数据库]：连接异常：{ex.Message}".RunLog(MessageLevelType.错误);
                return false;
            }

        }
        public bool CloseDB()
        {
            try
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                    conn.Dispose();
                }
                $"[数据库]：关闭成功".RunLog(MessageLevelType.成功);
                return true;
            }
            catch (Exception ex)
            {
                $"[数据库]：关闭异常：{ex.Message}".RunLog(MessageLevelType.错误);
                return false;
            }

        }

        public int Insert(string sql)
        {
            try
            {
                if (conn == null || conn.State == ConnectionState.Closed)
                    OpenDB();

                SqlCommand cmd = new SqlCommand(sql, conn);
                return cmd.ExecuteNonQuery();//返回影响的行数

            }
            catch (Exception ex)
            {
                $"[数据库]：插入数据异常：{ex.Message}".RunLog(MessageLevelType.错误);
                return  -1;
            }

        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int Query(string sql)
        {
            //try
            //{
            //    if (conn == null || conn.State == ConnectionState.Closed)
            //        OpenDB();

            //    SqlCommand cmd = new SqlCommand(sql, conn);
            //    return cmd.ExecuteNonQuery();//返回影响的行数

            //}
            //catch (Exception ex)
            //{
            //    $"[数据库]：插入数据异常：{ex.Message}".RunLog(MessageLevelType.错误);
            //    return -1;
            //}
            return -1;
        }
    }
}
